import json
import logging
import re

from django.contrib.auth import login
from django.shortcuts import render
from django.views import View
# Create your views here.
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.http import JsonResponse
from apps.oauth.utils import generate_access_token,check_access_token
from django_redis import get_redis_connection
from apps.oauth.models import OAuthQQUser
from apps.users.models import User

logger = logging.getLogger('django')


class QQAutho(View):
    def get(self, request):
        """
        点击qq登录发起第一次请求
        :param reuqest:
        :return:
        """
        # 获取参数
        text = request.GET.get('text', '/')  # 不是比传参数  设置默认值
        #  获取QQ登录页面网址
        # 创建OAuthQQ类的对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=text)

        # 调用对象的ge_qq_url方法 获取QQ扫码授权页面的地址
        login_url = oauth.get_qq_url()

        # 返回QQ登录授权地址
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'login_url': login_url
        })


class OauthCallback(View):
    def get(self, request):
        """
        授权成功  QQ会访问这个页面 并携带code
        :param request:
        :return:
        """
        code = request.GET.get('code')
        if not code:
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            })
        # 创建Oauth对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        # 通过code获取token
        try:
            token = oauth.get_access_token(code)

            openid = oauth.get_open_id(token)


        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code': 400,
                'errmsg': 'oauth2.0认证失败'
            })

        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)
        except Exception:
            access_token = generate_access_token(openid)
            return JsonResponse({
                'code': 300,
                'errmsg': 'ok',
                'access_token': access_token
            })
        user = oauth_qq.user

        login(request, user)

        response = JsonResponse({
            'code': 0,
            'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=14 * 24 * 3600)
        return response

    def post(self, request):
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get('mobile')
        password = data_dict.get('password')
        sms_code = data_dict.get('sms_code')
        access_token = data_dict.get('access_token')
        # 验证数据
        if not all([mobile, password, sms_code, access_token]):
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            })
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '请输入正确的手机号码'})

        # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400,
                                 'errmsg': '请输入8-20位的密码'})
        # 验证短信
        conn = get_redis_connection("verify_code")
        sms_code_server = conn.get('sms_%s' % mobile)
        if not sms_code_server:
            return JsonResponse({
                'code': 400,
                'errmsg': '验证码已过期'

            })
        if sms_code != sms_code_server.decode():
            return JsonResponse({
                'code': 400,
                'errmsg': '短信验证码错误'
            })

        # 获取openid解密
        openid = check_access_token(access_token)
        if not openid:
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少openid'
            })
        # 数据验证成功 判断用户是否已注册
        try:
            user = User.objects.get(mobile=mobile)
            # 取到用户  用户已存在 效验密码
            # 如果用户存在，检查用户密码
            if not user.check_password(password):
                return JsonResponse({'code': 400,
                                     'errmsg': '输入的密码不正确'})
        except Exception as e:
            # 用户不存在 创建用户

            user = User.objects.create_user(username=mobile,
                                            password=password,
                                            mobile=mobile)
        # 绑定openid
        try:
            OAuthQQUser.objects.create(
                openid=openid,
                user=user
            )
        except Exception as e :

            return JsonResponse({
                'code':400,
                'errmsg':'绑定失败'
            })
        # 状态保持
        login(request, user)
        response = JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })
        response.set_cookie('username', user.username,max_age=14*24*3600)
        return response
